# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'utility/distance_utils'
require 'utility/vec_utils'
require 'clustering/cluster'

class Hierarchical
  attr_accessor :clusters,:data,:ddmatrix, :max_dim, :k
  def initialize(matrix,k=5)
    @ddmatrix= DistanceUtils.ddmatrix(matrix)
    @max_dim= ((matrix.size/k).to_i+1)
    @k=k
    @data= matrix
    @clusters= []
    self.generate
  end
  def generate
    initial= rand(self.ddmatrix.size-1)
    far_away= VecUtils.far(self.ddmatrix[initial], (self.k))
    far_away.push(initial)
    far_away.each{|f|
      self.clusterize(f)
    }
  end
  def clusterize(centroide)
    cluster= Cluster.new(centroide, self.ddmatrix[centroide])
    candidate= VecUtils.near(self.ddmatrix[centroide], (self.ddmatrix.size))

    candidate.each{|c|
      if (cluster.elementi.size)<(self.max_dim) then
        if self.clusters==[] then
          cluster.add_element(c)
        elsif !(self.is_in(c))
          cluster.add_element(c)
        end
      end
    }
    if cluster.elementi!=[]
      self.clusters.push(cluster)
    end
  end
  def is_in(e)
    is= false

    self.clusters.each{|c|
      is= is || c.used(e)
    }

    return is
  end
  def clusters_energy
    energia= 0
    return self.clusters.each{|c|
      energia= energia+c.energia
    }
    
    return energia
  end
  def dataclust
    dclust= []

    self.clusters.each{|c|
      data= []
      c.elementi.each{|e|
        data.push(self.data[e])
      }
      dclust.push(data)
    }

    return dclust
  end
  def get_cluster(e)
    index= nil

    self.clusters.each{|c|
      if c.used(e) then
        index= clusters.index(c)
      end
    }

    return index
  end
  def clusters
    @clusters
  end
    def data
    @data
  end
    def ddmatrix
    @ddmatrix
  end
      def max_dim
    @max_dim
  end
  def k
    @k
  end
end
